#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost\asio.hpp>
#include <boost\algorithm\string.hpp>
#include <Message.h>

using namespace std;
using boost::asio::ip::tcp;

enum{ MAX_LENGTH = 1024 };


int main()
{
	try
	{
		boost::asio::io_service ioService;

		tcp::resolver resolver(ioService);
		tcp::resolver::query query(tcp::v4(), "localhost", "1313");
		tcp::resolver::iterator iterator = resolver.resolve(query);

		tcp::socket s(ioService);
		boost::asio::connect(s, iterator);

		int iMsgType = 0;

		while (iMsgType >= 0)
		{

			cout << "Enter message type: ";
			char msgType[MAX_LENGTH];
			cin.getline(msgType, MAX_LENGTH);
			int iMsgType = atoi(&msgType[0]);

			cout << "Enter message: ";
			char request[MAX_LENGTH];
			cin.getline(request, MAX_LENGTH);
			size_t requestLength = strlen(request);
			MessageHeader header(requestLength + 5, (MessageType::MessageType)iMsgType);
			std::string strMessage(request, requestLength);
			Message m(header, strMessage);

			std::string strBuffer = m.GetMessageBuffer();

			boost::asio::write(s, boost::asio::buffer(strBuffer.c_str(), strBuffer.length()));

			if ((MessageType::MessageType)iMsgType == MessageType::ANY_MESSAGE_FOR_ME)
			{
				vector<char> replyHeader(5);
				boost::asio::read(s, boost::asio::buffer(replyHeader));

				int messageLength = 0;
				messageLength |= replyHeader[0] << 24;
				messageLength |= replyHeader[1] << 16;
				messageLength |= replyHeader[2] << 8;
				messageLength |= replyHeader[3];

				int msgType = replyHeader[4];

				if (msgType != MessageType::NO_MESSAGES_FOR_YOU)
				{


					vector<char> replyMessage(messageLength - replyHeader.size());
					boost::asio::read(s, boost::asio::buffer(replyMessage));

					string strMsg(replyMessage.data(), replyMessage.size());
					vector<string> subStrings;
					boost::split(subStrings, strMessage, boost::is_any_of(" "));
					cout << strMsg << endl;
				}
				else
				{
					cout << "No messages found!" << endl;
				}

			}

		}

		system("pause");

	}
	catch (std::exception &e)
	{
		std::cerr << "Exception: " << e.what() << std::endl;
	}


	return 0;
}